package king.dominic.jorc.core;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;

import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.File;

import king.dominic.jlibrary.util.BitmapUtils;

/**
 * Created by DominicKing on 2017/10/25.
 * OCR
 */

public class OCR {
    private final String TAG = getClass().getSimpleName();
    private final TessBaseAPI api;
    private boolean isInitialize = false;
    private Listener.OnSuccessfulListener listener;
    private String mWhiteList = "";
    private String mBlackList = "";

    private Listener.Callback<Object> getIDCardInformationCallbackInner;

    enum Language {
        CHINESE_SIMPLE("chi_sim"), ENGLISH("eng");

        public final String language;
        public final String zipFileName;
        public final String traineddataFileName;
        public final String config;

        Language(String language) {
            this.language = language;
            this.zipFileName = language + ".zip";
            this.traineddataFileName = language + ".traineddata";
            this.config = language + ".config";
        }
    }

    public OCR() {
        api = new TessBaseAPI();
    }

    public boolean isInitialize() {
        return isInitialize;
    }

    private Listener.OnSuccessfulListener mOnSuccessfulListener = new Listener.OnSuccessfulListener() {
        @Override
        public void success(boolean yes) {
            resumeROC();
            isInitialize = yes;
            if (listener != null) listener.success(yes);
        }
    };

    public void init(Context context, final Listener.OnSuccessfulListener listener) {
        isInitialize = false;
        this.listener = listener;
        new InitializeORCAsyncTask.Builder(api)
                .with(context)
                .language(Language.CHINESE_SIMPLE)
                .onSuccessfulListener(mOnSuccessfulListener)
                .build()
                .execute();
    }

    public void parseFrontCard(RecycledBitmap bitmap, Listener.Callback<Object> callback) {
        getIDCardInformationCallbackInner = callback;
        new GetUTF8TextAsyncTask.Builder(api)
                .callback(getIDCardInformationCallbackInner)
                .isBack(false)
                .build()
                .execute(bitmap);
    }

    public void parseBackCard(RecycledBitmap bitmap, Listener.Callback<Object> callback) {
        getIDCardInformationCallbackInner = callback;
        new GetUTF8TextAsyncTask.Builder(api)
                .callback(getIDCardInformationCallbackInner)
                .isBack(true)
                .build()
                .execute(bitmap);
    }

    /**
     * 设置白名单
     */
    public void setWhiteList(String whiteList) {
        mWhiteList = whiteList;
        if (isInitialize)
            api.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, whiteList);
    }

    /**
     * 设置黑名单
     */
    public void setBlackList(String blackList) {
        mBlackList = blackList;
        if (isInitialize)
            api.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, blackList);
    }

    public void destroy() {
//        api.clear();
//        api.end();
    }

    public void resumeROC() {
        api.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_BLOCK);
//        api.setVariable(TessBaseAPI.VAR_SAVE_BLOB_CHOICES, "");
        api.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "{~`!@#$%^&*()_+=|\\<,>?/\"':;'·！@#￥%……&*（）——+=｛【：；“‘《，。？、》’”】｝}′");
//        api.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, mWhiteList);
    }

    public static class RecycledBitmap {

        final Bitmap bitmap;
        final Rect rect;
        volatile boolean canRecycled = false;

        /**
         * @param bitmap 位图
         * @param rect   有效区域
         */
        public RecycledBitmap(Bitmap bitmap, Rect rect) {
            this.bitmap = bitmap;
            this.rect = rect;
        }

        /**
         * 是否不可用
         *
         * @return true 不可用
         */
        public boolean isUseless() {
            return bitmap == null || bitmap.isRecycled();
        }

        /**
         * 确保两边都是用完后销毁
         */
        public void autoRecycled() {
            if (canRecycled) recycled();
            else canRecycled = true;
        }

        /**
         * 直接销毁
         */
        public void recycled() {
            if (bitmap != null && !bitmap.isRecycled()) bitmap.recycle();
        }

        /**
         * 保存
         *
         * @param file 文件
         */
        public void save(File file) {
            BitmapUtils.compress(bitmap, 85, file, 800);
        }
    }

}
